// 1. Form.create()(CreateForm); 是新建一个form的，不同的form，不同的校验
// 2. children
 //   handleImportAction: ƒ (fields)
// handleImportVisible: ƒ (flag)
// importModalVisible: false
// onDownloadTemp: ƒ ()
// children: {$$typeof: Symbol(react.element), key: "submit", ref: null, props: {…}, type: ƒ, …}
// __proto__: Object

import { Form, Input, Modal, InputNumber, Button, Select, DatePicker } from 'antd';
import React from 'react';
import { len, first } from './common';
import { rangedate2str, date2str, today } from './moment';
import moment from 'moment';

const FormItem = Form.Item;
const { Option } = Select;

export const list2options = (params) => {
  let { list, placeholder, style, key, val } = params;
  style = style || {width:300};
  key = key || 'id';
  val = val || 'name';
  return (
    <Select placeholder={placeholder} style={style}>
      {
        len(list)
        && list.map(v => <Option key={v[key]} value={v[key]} >{v[val]}</Option>)
      }
    </Select>
  );
}

export const list2filters = (params, kk='id', vk='name') => {
  // 支持全部
  if (len(params)) {
    params = JSON.parse(JSON.stringify(params)); // Deep copy

    const all = {};
    all[kk] = 'undefined', // FIXME: 这个在接口层会被忽略的，魔数
    all[vk] = '全部';
    params.unshift(all);

    return len(params) 
    && 
    params.map(v => <Option value={v[kk]} key={v[kk]}>{v[vk]}</Option>);
  } 
  
  return null;
  
}

export const enum2options = (enumMap, placeholder, style={width:300}) => {
  return (
    <Select placeholder={placeholder} style={style}>
      {
        enumMap.map(val => (
          <Option key={val.enum_desc} value={val.enum_value}>{val.enum_desc}</Option>
        ))
        
      }
    </Select>
  )
}

// enum2options 的补充，配合beans中的枚举
export const ccEnumToOptions = (enumMap, placeholder, style={width:300}) => {
  return (
    <Select placeholder={placeholder} style={style}>
      {
        Object.keys(enumMap).map(key => (
          <Option key={key} value={key}>{enumMap[key]}</Option>
        ))
      }
    </Select>
  )
}

export const validateAndCommit = (props, extra) => {
  const {form, commitHandler} = props;

  form.validateFields((err, fields) => {
    if (err) return;
    form.resetFields();
  
    commitHandler && commitHandler({
      ...fields,
      ...extra
    });
  });
}

/**
 * fields to states
 * 
 * 魔字段修改：
 * 
 * date_range
 * date_month_range
 * 
 * date_month
 * dragger
 */
export const fields2states = (fields, prevState) => {
  let values = { ...fields };

  if (values['date_range']) {
    const [start_date, end_date] = rangedate2str(values['date_range'], 'YYYY-MM-DD HH:mm:ss');
    const [start_time, end_time] = rangedate2str(values['date_range'], 'YYYY-MM-DD');// FIXME: 完全是为了适配多种命名，烦躁
    delete values['date_range'];

    values = {
      ...values,
      start_date,
      end_date,
      start_time,
      end_time,
    };
  } 


  if (values['date_month_range']) {
    const [start_date, end_date] = rangedate2str(values['date_month_range'], 'YYYY-MM');
    const [start_time, end_time] = rangedate2str(values['date_month_range'], 'YYYY-MM');// FIXME: 完全是为了适配多种命名，烦躁
    delete values['date_month_range'];

    values = {
      ...values,
      start_date,
      end_date,
      start_time,
      end_time,
    };
  }
  
  if (values['date_month']) {
    const date = date2str(values['date_month'], 'YYYY-MM');
    const time = date;
    delete values['date_month'];

    values = {
      ...values,
      date,
      time,
    };
  }

  if (values['dragger']) {
    const file = first(values['dragger']);

    delete values['dragger'];

    values = {
      ...values,
      file,
    };
  }

  if (prevState) {
    return {
      ...prevState,
      ...values,
    }
  }

  return values;
}
export const fields2params = fields2states;
// 隐藏转化
export const convertParams = fields2states;

/**
 * 时间表单
 */
export const createDateRangeForm = ({ form, onChange, values }) => {
  const { RangePicker } = DatePicker;
  const dateFormat = 'YYYY-MM-DD';
  let { startTime, endTime } = values || {};

  if (!startTime || !endTime) {
    startTime = endTime = today();
  }

  return (
    <FormItem>
      {form.getFieldDecorator('date_range', {
        initialValue: [moment(startTime, dateFormat), moment(endTime, dateFormat)]
      })(
        <RangePicker 
          onChange={onChange}
          format={dateFormat}
          placeholder={['开始时间','结束时间']}
          />
      )}
    </FormItem>
  );
}

/**
 * 返回一个表单创建函数
 * 
 * 基本参数
 * 

 */
export const createForm = ({
  styles,
  configs,

}) => {
  // 默认配置
  styles = styles || {
    model: {
      width: 700
    },
    buttons: {
      commit: {
        marginRight: 40
      },
      cancel: {

      }
    }
  };


  /**
   * 表单域
   * 
   * visiable 是否显示
   * hideHandler 隐藏句柄
   * commitHandler 提交句柄
   * cancelHandler 取消句柄
   */
  return (props) => {
    const { visible, hideHandler, cancelHandler, commitHandler, values, form } = props;

    const onCommit = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        form.resetFields();

        commitHandler({
          ...fieldsValue,
          id: values.id
        });
      });
    }

    return (
      <Modal
        destroyOnClose
        title="编辑"
        visible={visible}
        onOk={onCommit}
        onCancel={cancelHandler}
        footer={[
          <Button key="submit" type="primary" onClick={onCommit} style={styles.buttons.commit}>
            保存
          </Button>,
          <Button key="back" onClick={hideHandler}>
            取消
          </Button>,
        ]}
        width={700}
      >
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="品牌编码">
          {form.getFieldDecorator('brandId', {
            initialValue: formVals.brandId,
            rules: [
              {
                required: true,
                message: '请输入至少一个字符的品牌编码！',
                min: 1,
              },
            ],
          })(<Input placeholder="请输入品牌编码" />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="品牌名称">
          {form.getFieldDecorator('brandName', {
            initialValue: formVals.brandName,
            rules: [{required: true}]
          })(<Input placeholder="请输入品牌名称" />)}
        </FormItem>
        <Form.Item label="业态" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
          {form.getFieldDecorator('brandType', {
            initialValue: formVals.brandType,
            rules: [{required: true}]
          })(
            enum2options(enumsMap.brand_type_status, "请选择业态", { width: 300 })
          )}
        </Form.Item>
        <Form.Item label="合作类型" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
          {form.getFieldDecorator('brandBusinessType', {
            initialValue: formVals.brandBusinessType,
            rules: [{required: true}]
          })(
            enum2options(enumsMap.shop_business_type, "请选择合作类型", { width: 300 })
       
          )}
        </Form.Item>
        <Form.Item label="经营类型" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
          {form.getFieldDecorator('brandJoinType', {
            initialValue: formVals.brandJoinType,
            rules: [{required: true}]
          })(
            enum2options(enumsMap.brand_deduct_point_type, "请选择经营类型", { width: 300 })
          )}
        </Form.Item>
        <Form.Item label="品牌状态" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
          {form.getFieldDecorator('brandStatus', {
            initialValue: formVals.brandStatus,
            rules: [{required: true}]
          })(
            enum2options(enumsMap.brand_status, "请选择品牌状态", { width: 300 })
          )}
        </Form.Item>
      </Modal>
    );
  }
}